import pygame
import spyral

import Dic


class Timer(spyral.sprite.Sprite):
    def __init__(self, speed):
        spyral.sprite.Sprite.__init__(self)
        self.images = [];
        self.images.append(pygame.image.load(Dic.images['timer1']))
        self.images.append(pygame.image.load(Dic.images['timer2']))
        self.images.append(pygame.image.load(Dic.images['timer3']))
        self.images.append(pygame.image.load(Dic.images['timer4']))
        self.image = self.images[0].copy();
        self.img_num = 0;
        
        self.countdown_img = []
        self.countdown_img.append(pygame.image.load(Dic.images['timer_num1']))
        self.countdown_img.append(pygame.image.load(Dic.images['timer_num2']))
        self.countdown_img.append(pygame.image.load(Dic.images['timer_num3']))

        self.pos = (-25, 520);
        self.layer = 3;
        
        self.count = 0; #keeps track of when to update the animation
        self.countdown = 0; #keeps track of the 3 2 1 countdown
        self.speed = speed; #determines speed of timer
        
        self.timesup = False;
        
    def update(self, tick):
        if (self.timesup == False):
            #cycle through animation
            if (self.count == 5):
                self.count = 0;
                self.animate();
            else:
                self.count += 1;
            #update position    
            self.pos = (self.pos[0] + 8 * (1 + (self.speed*.1)), self.pos[1])
            
            #display countdown image
            if ((Dic.geom['width'] / 6) * 5 <= self.pos[0]):
                self.countdown = 1;
                self.image = self.images[self.img_num].copy()
                self.image.blit(self.countdown_img[0], (0,0))
            elif ((Dic.geom['width'] / 6) * 4 <= self.pos[0]):
                self.countdown = 2;
                self.image = self.images[self.img_num].copy()
                self.image.blit(self.countdown_img[1], (0,0))
            elif ((Dic.geom['width'] / 6) * 3 <= self.pos[0]):
                self.countdown = 3;
                self.image.blit(self.countdown_img[2], (0,0))
            
            #check if times up
            if (Dic.geom['width'] <= self.pos[0]):
                self.timesup = True;

    
    def animate(self):
        if (self.img_num == 3):
            self.img_num = 0;
        else:
            self.img_num += 1;
        
        self.image = self.images[self.img_num].copy();
        if (self.countdown != 0):
            self.image.blit(self.countdown_img[self.countdown - 1], (0,0))
    
    def timesUp(self):
        return self.timesup;
    
    def getTime(self):
        return float(self.pos[0]) / Dic.geom['width'];
            